package com.memory.monitor.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.memory.monitor.common.DeleteRequest;
import com.memory.monitor.common.ErrorCode;
import com.memory.monitor.constant.ExcelConstant;
import com.memory.monitor.exception.BusinessException;
import com.memory.monitor.exception.ThrowUtils;
import com.memory.monitor.job.AreaExcelListener;
import com.memory.monitor.job.InstitutionExcelListener;
import com.memory.monitor.job.JobExcelListener;
import com.memory.monitor.mapper.JobMapper;
import com.memory.monitor.model.dto.job.JobAddRequest;
import com.memory.monitor.model.dto.job.JobQuerryRequest;
import com.memory.monitor.model.dto.job.JobUpdateRequest;

import com.memory.monitor.model.entity.Area;
import com.memory.monitor.model.entity.Institution;
import com.memory.monitor.model.entity.Job;

import com.memory.monitor.model.entity.User;
import com.memory.monitor.model.vo.InstitutionVO;
import com.memory.monitor.model.vo.JobVO;
import com.memory.monitor.service.JobService;
import com.memory.monitor.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.memory.monitor.constant.ExcelConstant.*;

/**
* @author 21731
* @description 针对表【job(岗位管理)】的数据库操作Service实现
* @createDate 2024-09-02 09:59:52
*/
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job>
    implements JobService {
    @Resource
    private UserService userService;

    /**
     * 封装JobVO对象
     * @param job
     * @return
     */
    @Override
    public JobVO getjobVO(Job job) {
        if (job == null) {
            return null;
        }
        JobVO jobVO = new JobVO();
        BeanUtils.copyProperties(job, jobVO);
        return jobVO;
    }

    /**
     * 封装JobVO对象
     * @param jobList
     * @return
     */
    @Override
    public List<JobVO> getjobVO(List<Job> jobList) {
        if (CollectionUtils.isEmpty(jobList)) {
            return new ArrayList<>();
        }
        return jobList.stream().map(this::getjobVO).collect(Collectors.toList());
    }

    /**
     * 查询岗位信息
     * @param jobQuerryRequest
     * @return
     */
    @Override
    public QueryWrapper<Job> getQueryWrapper(JobQuerryRequest jobQuerryRequest) {
        if (jobQuerryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = jobQuerryRequest.getId();
        String jobTitle = jobQuerryRequest.getJobTitle();
        String addressId = jobQuerryRequest.getAddressId();
        String type = jobQuerryRequest.getType();
        Integer status = jobQuerryRequest.getStatus();

        QueryWrapper<Job> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.like(StringUtils.isNotBlank(jobTitle), "job_title", jobTitle);
        queryWrapper.eq(StringUtils.isNotBlank(addressId), "address_id", addressId);
        queryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
        queryWrapper.eq(status!=null, "status", status);
        return queryWrapper;
    }

    /**
     * 添加岗位信息
     * @param jobAddRequest
     * @return
     */
    @Override
    public Long addJob(JobAddRequest jobAddRequest) {
        if (jobAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Job job = new Job();

        BeanUtils.copyProperties(jobAddRequest, job);
        boolean result = this.save(job);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return job.getId();
    }

    /**
     * 更新岗位信息
     * @param jobUpdateRequest
     * @return
     */
    @Override
    public Boolean updateJob(JobUpdateRequest jobUpdateRequest) {
        if (jobUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }


       //修改用户表中的岗位信息
        String jobTitle = jobUpdateRequest.getJobTitle();
        Job job = this.getById(jobUpdateRequest.getId());
        // 如果找不到对应的Area对象，可以选择抛出异常或返回错误
        ThrowUtils.throwIf(job == null,ErrorCode.PARAMS_ERROR);
        List<User> userlist = userService.lambdaQuery()
                .eq(User::getJob, job.getJobTitle()).list();
        for (User user : userlist) {
            user.setJob(jobTitle);
        }
        userService.updateBatchById(userlist);

        //修改岗位表中的岗位信息
        BeanUtils.copyProperties(jobUpdateRequest,job);
        boolean result = this.updateById(job);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return result;
    }

    /**
     * 删除岗位信息
     * @param deleteRequest
     * @return
     */
    @Override
    public Boolean deleteJob(DeleteRequest deleteRequest) {
        if (deleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建查询请求，设置ID
        Job job = this.getById(deleteRequest.getId());
        // 如果找不到对应的job对象，可以选择抛出异常或返回错误
        ThrowUtils.throwIf(job == null,ErrorCode.PARAMS_ERROR);

        //在user表中查询job_title相同的字段 进行同步删除
        List<User> userList = userService.lambdaQuery()
                .eq(User::getJob, job.getJobTitle()).list();

        userService.removeBatchByIds(userList);

        //删除该表中的信息
        boolean result = this.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(result, ErrorCode.OPERATION_ERROR);
        return result;
    }

    @Override
    public List<JobVO> listJobByPage() {
        return getjobVO(this.list());
    }

    @Override
    public Boolean readExcel(MultipartFile multipartFile) {
        // 1.转换文件为字节流
        InputStream inputStream;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 2.执行文件处理逻辑
        EasyExcel.read(inputStream, Job.class, new JobExcelListener()).sheet().doRead();
        // 3.入库
        boolean saveBatch = this.saveBatch(JobExcelListener.CACHED_DATA_LIST);

        ThrowUtils.throwIf(!saveBatch, ErrorCode.PARAMS_ERROR);
        return true;
    }

    @Override
    public Boolean writeExcel(String path) {
        // 1.定义文件路径
        String fullPath = DOWNLOAD_PATH + AREA_TABLE_NAME;
        // 2.检查文件是否存在
        ExcelConstant.isExist(fullPath);
        // 3.根据路径导出
        List<JobVO> jobList = this.listJobByPage();
        EasyExcel.write(fullPath, User.class).sheet(AREA_SHEET_NAME).doWrite(jobList);

        return true;
    }


}




